﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NMF.Optimizations
{
    public abstract class ObservableSourceBase<T> : IObservableSource<T>
    {
        public abstract IEnumerator<T> GetEnumerator();

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        private List<ISourceObserver<T>> observers = new List<ISourceObserver<T>>();

        protected virtual void OnNewItem(T item)
        {
            foreach (var observer in observers.ToArray())
            {
                observer.OnNewItem(item);
            }
        }

        protected virtual void OnUpdatedItem(T item)
        {
            foreach (var observer in observers.ToArray())
            {
                observer.OnUpdatedItem(item);
            }
        }

        protected virtual void OnDeletedItem(T item)
        {
            foreach (var observer in observers.ToArray())
            {
                observer.OnDeletedItem(item);
            }
        }

        protected virtual void OnReset()
        {
            foreach (var observer in observers.ToArray())
            {
                observer.OnReset();
            }
        }


        public void Subscribe(ISourceObserver<T> observer)
        {
            if (observer != null)
            {
                observers.Add(observer);
            }
        }

        public IEnumerable<T> AsEnumerable()
        {
            return this;
        }

        public bool Unsubscribe(Predicate<object> filter)
        {
            if (filter == null) throw new ArgumentNullException("filter");
            for (int i = observers.Count - 1; i >= 0; i--)
            {
                var observer = observers[i];
                if (filter(observer))
                {
                    observers.RemoveAt(i);
                    return true;
                }
            }
            return false;
        }
    }
}
